package com.xxdh.interceptor;

import com.xxdh.util.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return true;
        }
        //解析用户信息
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("userId".equals(name)) {
                UserHolder.setUserId(Long.parseLong(cookie.getValue()));
                break;
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除用户信息
        UserHolder.removeUser();
    }
}
